/*
 * 
 * 
 * 
 */
package com.cms.template.directive;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.cms.utils.FreeMarkerUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 模板指令 - SQL分页
 * 
 * 
 * 
 */
@Component
public class SqlPageDirective extends BaseDirective {

    /** "页码"参数名称 */
    private static final String PAGE_NUMBER_PARAMETER_NAME = "pageNumber";
    
    /** "每页记录数"参数名称 */
    private static final String PAGE_SIZE_PARAMETER_NAME = "pageSize";

    /** "SQL"参数名称 */
    private static final String SQL_PARAMETER_NAME = "sql";

	/** 变量名称 */
	private static final String VARIABLE_NAME = "recordPage";

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		Integer pageNumber = FreeMarkerUtils.getParameter(PAGE_NUMBER_PARAMETER_NAME, Integer.class, params);
		Integer pageSize = FreeMarkerUtils.getParameter(PAGE_SIZE_PARAMETER_NAME, Integer.class, params);
        String sql = FreeMarkerUtils.getParameter(SQL_PARAMETER_NAME, String.class, params);
		Page<Map<String,Object>> page = SqlRunner.db().selectPage(new Page<>(pageNumber, pageSize), sql);
        setLocalVariable(VARIABLE_NAME, page, env, body);
	}
}